/*
----------------------------------------------------------------------------------------------------
This source file is part of the Gamut Framework
Copyright (c) 2007 by Ryan Holcombe

This program is free software; you can redistribute it and/or modify it under the terms of the GNU
Lesser General Public License as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version.
----------------------------------------------------------------------------------------------------
*/


#include "GamutFramework.h"
#include "GamutLogger.h"
#include "GamutLogFile.h"
#include "GamutProfiler.h"
#include "GamutConsole.h"
#include "GamutManagerFactory.h"


namespace Gamut
{
	// -------------------------------------------------------------------------------------------//
	Framework::Framework()
	{
		// create a logger based on the debug level
		#ifdef _DEBUG
			new Logger(INFORMATIONAL);
		#else
			new Logger();
		#endif
	}

	// -------------------------------------------------------------------------------------------//
	Framework::~Framework()
	{
		if (Logger::getSingletonPtr())
			delete Logger::getSingletonPtr();
	}

	// -------------------------------------------------------------------------------------------//
	void Framework::go()
	{
		init();
		setup();
		run();
		cleanup();
		destroy();
	}
	
	// -------------------------------------------------------------------------------------------//
	void Framework::init()
	{
		// create a log file
		assert(Logger::getSingletonPtr());
		Logger::getSingleton().addListener(IListenerPtr(new LogFile()));

		new Profiler();
		new Console();
		new ManagerFactory();

		LOG4("Gamut::Framework::init completed successfully");
	}
	
	// -------------------------------------------------------------------------------------------//
	void Framework::run()
	{
		Gamut::Timer timer;
		double lastTime = 0.0;
		double currentTime;
		double elapsed;

		do
		{
			// calculate the time in seconds since the last frame
			currentTime = timer.getSeconds();
			elapsed = (currentTime - lastTime);
			if (elapsed < 0.001)
				elapsed = 0.001;
			lastTime = currentTime;

			ManagerFactory::getSingleton().tick(elapsed);

		} while (updateFrame(elapsed));
		
		LOG4("Gamut::Framework::run completed successfully");	
	}
	
	// -------------------------------------------------------------------------------------------//
	void Framework::destroy()
	{
		delete Console::getSingletonPtr();
		delete Profiler::getSingletonPtr();
		delete ManagerFactory::getSingletonPtr();
		LOG4("Gamut::Framework::destroy completed successfully");
	}
}
